package com.nerins.udp.server;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

public class RBACRequestEncoder implements ProtocolEncoder {

    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
        int bufLen = 0;

    	RBACRequest request = (RBACRequest) message;

        //type
        bufLen += Integer.SIZE /8;
        
        //version
        bufLen += Integer.SIZE /8;
        
        //id
        final byte[] requestId = request.getRequestId().getBytes("ISO-8859-1");

        //id len
        bufLen += requestId.length;

        //params
        final byte[] csvParams = request.getCsvParams().getBytes("ISO-8859-1");

        //params len
        bufLen += csvParams.length;
        
        //buffer to write
        IoBuffer buffer = IoBuffer.allocate(bufLen, false);
        
        buffer.putInt(request.getRequestType());
        buffer.putInt(request.getRequestVersion());
        buffer.putInt(requestId.length);
        buffer.put(requestId);
        buffer.putInt(csvParams.length);
        buffer.put(csvParams);
        buffer.flip();
        out.write(buffer);
    }

    public void dispose(IoSession session) throws Exception {
        // nothing to dispose
    }
}